import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/AppConfig/ShowDialog.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../Authentication/AuthenticationModel/DriverCardModel.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'package:image/image.dart' as img;

import 'ShowImageView.dart';
class EditDriverCard extends StatefulWidget {
  const EditDriverCard({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<EditDriverCard> createState() => _EditDriverCardState();
}

class _EditDriverCardState extends State<EditDriverCard> {
  List titleList=["姓名","驾驶证号","准驾车型","有效起始日期","有效结束日期","发证机关","档案编号"];
  List dataList =["","","","","","",""];
  TextEditingController _nametextEditingController = TextEditingController();
  final ImagePicker picker = new ImagePicker();
//用户本地图片
  File? _userImage;
  File? _userImage2;//存放获取到的本地路径
  int oneCheck =0;
  String cardImgStr="";
  String cardImgStr2="";
  Map dataMap={};
  String getfrontPath="";
  String getbackPath="";
  bool isEdit=true;
  bool isShowError=false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.dataMap['driverLicenseInfo']!=null) {
      isEdit= false;
      dataList = [
        widget.dataMap['driverLicenseInfo']['realName'],
        widget.dataMap['driverLicenseInfo']['licenseNum'],
        widget.dataMap['driverLicenseInfo']['vehicleClass'],
        widget.dataMap['driverLicenseInfo']['validPeriodTo'],
        widget.dataMap['driverLicenseInfo']['validPeriodFrom'],
        widget.dataMap['driverLicenseInfo']['issuingOrganizations'],
        widget.dataMap['driverLicenseInfo']['fileNum']
      ];
      if (widget.dataMap['driverLicenseInfo']['frontPath'] != null) {
        getfrontPath = widget.dataMap['driverLicenseInfo']['frontPath'];
        getbackPath = widget.dataMap['driverLicenseInfo']['backPath'];
      }
    }
  }

  DriverCardModel cardModel = DriverCardModel(DriverPic: "",
    DriverPic2: "",name: "",
    DriverNum: "",CarStyle: "",
    StartTime: "",EndTime: "",
    CardOfficeName: "",FileNum: "",);

  Future<DateTime?> _showDatePickerForTheme(BuildContext context) {
    return showDatePicker(
      context: context, // 上下文
      initialDate: DateTime.now(), // 初始化选中日期
      firstDate: DateTime.now(), // 开始日期
      lastDate: DateTime(2100, 1), // 结束日期
      currentDate: DateTime.now(), // 当前日期
      initialEntryMode: DatePickerEntryMode
          .calendarOnly, // 日历弹框样式 calendar: 默认显示日历，可切换成输入模式，input:默认显示输入模式，可切换到日历，calendarOnly:只显示日历，inputOnly:只显示输入模式
      selectableDayPredicate: (dayTime) {
        // 自定义哪些日期可选
        if (dayTime == DateTime(2022, 1, 1) || dayTime == DateTime(2100, 1, 1)) {
          return false;
        }
        return true;
      },
      builder: (context, child) {
        return Theme(
          data: ThemeData(
            primarySwatch: Colors.amber,
          ),
          child: child!,
        );
      },
      helpText: "请选择日期", // 左上角提示文字
      cancelText: "取消", // 取消按钮 文案
      confirmText: "确定", // 确认按钮 文案
      initialDatePickerMode: DatePickerMode.day, // 日期选择模式 默认为天
      useRootNavigator: true, // 是否使用根导航器
      textDirection: TextDirection.ltr, // 水平方向 显示方向 默认 ltr
    );
  }
  void uploadOcrAction()  {

    ApiManager.postData(
      context,
      'api/system/dev/ocr/doOcr',
      {
        "type": "DL",
        "frontFileFormat": "jpg",
        "frontData": cardImgStr,
        "backFileFormat":"jpg",
        "backData": cardImgStr2,
      },
          (responseData) {
        setState(() {
          BrnToast.show("识别成功", context, duration: BrnDuration.short,);
          dataMap=responseData['data']['result'];
          dataList=[dataMap['name'],dataMap['idcard'],dataMap['quasiDriveType'],
            dataMap['beginDate'],dataMap['endDate'],dataMap['issuingAuthority'],dataMap['fileNumber']];
          getfrontPath=responseData['data']['frontPath'];
          getbackPath=responseData['data']['backPath'];
        });
      },
    );

  }
  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);

    oneCheck==1?
    cardImgStr =base64String
        :cardImgStr2 =base64String;
    uploadOcrAction();

  }

  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text("驾驶证",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        centerTitle: true,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Column(
        children: [
          Expanded(child:
          ListView(

            children: [


              Container(
                color: Colors.white,
                height: 140.h,
                child:Column(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Text("上传驾驶证(必填)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),

                      ],
                    ),

                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,

                      children: [
                        GestureDetector(
                          child:
                          getfrontPath!=""&&_userImage==null?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getfrontPath ,height: 90.h,width: 150.w,fit: BoxFit.cover,),
                              ),
                              if(isEdit)
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )
                              :getfrontPath!=""&&_userImage!=null?
                          Stack(

                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child: Image.file(_userImage!,height: 90.h,width: 150.w,fit: BoxFit.cover,) ,
                              ),
                              if(isEdit)
                                Center(
                                  child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                                ),
                            ],
                            alignment: Alignment.center,
                          )

                              :
                          Image.asset("lib/Images/Authentication/上传驾驶证主页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            if(isEdit==false){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ShowImageViewer( (MyServiceUrl.imgHeader+getfrontPath).toString()),
                                ),
                              );
                            }else {
      showModalBottomSheet(context: context, builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child:
          Stack(

            children: [

              Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,

                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      IconButton(onPressed: () {
                        Navigator.of(context).pop();
                      }, icon: Icon(Icons.close, color: MyColors.textColor,)),
                    ],
                  ),
                  Text(messages["示例"],
                    style: TextStyle(color: Colors.black, fontSize:
                    14.sp),),
                  SizedBox(height: 8.h,),
                  Image.asset('lib/Images/Authentication/驾驶证主页示例图.png',
                    width: 2270.w, height: 145.h,),


                  SizedBox(height: 8.h,),
                  Text(messages["请按照示例上传"],
                    style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                  Text(messages["模糊、遮挡会导致证件无法识别，认证不通过"],
                    style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                  SizedBox(height: 8.h,),
                  Text(messages["上传照片"], style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w600,
                      fontSize: 18.sp),),
                  SizedBox(height: 10.h,),
                  Row(
                    children: [
                      SizedBox(width: 38.w,),
                      GestureDetector(
                        child: Column(
                          children: [
                            Image.asset(
                              "lib/Images/Authentication/相册icon.png",
                              width: 35.w, height: 35.h,),
                            Text(messages["相册"], style: TextStyle(
                                color: Colors.black),),

                          ],

                        ),
                        onTap: () async {
                          var status = await Permission.photos.request();

                          if(status==PermissionStatus.denied){
                            showPhotosFirstDialog(context);
                          }else if(status==PermissionStatus.permanentlyDenied){
                            showPhotosDialog(context);
                          }else {
                            Navigator.of(context).pop();
                            final pickedFile = await picker.pickImage(
                                source: ImageSource.gallery);

                            if (pickedFile != null) {
                              setState(() {
                                oneCheck = 1;
                                _userImage = File(pickedFile.path);
                                printImageMemorySize(_userImage!);
                                print(_userImage);
                                compressImage(_userImage!);
                              });
                            }
                          }
                        },
                      ),

                      SizedBox(width: 38.w,),
                      GestureDetector(
                        child: Column(
                          children: [
                            Image.asset(
                              "lib/Images/Authentication/拍照icon.png",
                              width: 35.w, height: 35.h,),
                            Text(messages["拍照"], style: TextStyle(
                                color: Colors.black),),

                          ],

                        ),
                        onTap: () async {
                          var status = await Permission.camera.request();
                          if(status==PermissionStatus.denied){
                            showCameraFirstDialog(context);
                          }else if(status==PermissionStatus.permanentlyDenied){
                            showCameraDialog(context);
                          }else {
                            Navigator.of(context).pop();
                            final pickedFile = await picker.pickImage(
                                source: ImageSource.camera);

                            if (pickedFile != null) {
                              setState(() {
                                oneCheck = 1;
                                _userImage = File(pickedFile.path);
                                printImageMemorySize(_userImage!);
                                print(_userImage);
                                compressImage(_userImage!);
                              });
                            }
                          }
                        },
                      ),

                    ],
                  ),
                  SizedBox(height: 30.h,),
                ],

              ),

            ],

          ),
        );
      });
    }
                          },
                        ),
                        SizedBox(width: 20.w,),
                        GestureDetector(
                          child:
                          getbackPath!=""&&_userImage2==null?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getbackPath ,height: 90.h,width: 150.w,fit: BoxFit.cover,),
                              ),
                              if(isEdit)
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )
                              :getbackPath!=""&&_userImage2!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,
                                child: Image.file(_userImage2!,height: 90.h,width: 150.w,fit: BoxFit.cover,) ,
                              ),
                              if(isEdit)
                                Center(
                                  child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                                ),
                            ],
                            alignment: Alignment.center,
                          ):
                          Image.asset("lib/Images/Authentication/上传驾驶证副页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            if(isEdit==false){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => ShowImageViewer( (MyServiceUrl.imgHeader+getbackPath).toString()),
                                ),
                              );
                            }else {
                              showModalBottomSheet(context: context,
                                  builder: (BuildContext context) {
                                    return Container(
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10))),
                                      child:
                                      Stack(

                                        children: [

                                          Column(
                                            mainAxisSize: MainAxisSize.min,
                                            mainAxisAlignment: MainAxisAlignment
                                                .center,

                                            children: [
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment
                                                    .end,
                                                children: [
                                                  IconButton(onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                      icon: Icon(Icons.close,
                                                        color: MyColors
                                                            .textColor,)),
                                                ],
                                              ),
                                              Text(messages["示例"],
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 14.sp),),
                                              SizedBox(height: 8.h,),
                                              Image.asset(
                                                'lib/Images/Authentication/驾驶证副页示例图.png',
                                                width: 2270.w, height: 145.h,),


                                              SizedBox(height: 8.h,),
                                              Text(messages["请按照示例上传"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              Text(
                                                messages["模糊、遮挡会导致证件无法识别，认证不通过"],
                                                style: TextStyle(
                                                    color: Color.fromRGBO(
                                                        102, 102, 102, 1)),),
                                              SizedBox(height: 8.h,),
                                              Text(messages["上传照片"],
                                                style: TextStyle(
                                                    color: Colors.black,
                                                    fontWeight: FontWeight.w600,
                                                    fontSize: 18.sp),),
                                              SizedBox(height: 10.h,),
                                              Row(
                                                children: [
                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/相册icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["相册"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),

                                                      ],

                                                    ),
                                                    onTap: () async {
                                                      var status = await Permission.photos.request();

                                                      if(status==PermissionStatus.denied){
                                                        showPhotosFirstDialog(context);
                                                      }else if(status==PermissionStatus.permanentlyDenied){
                                                        showPhotosDialog(context);
                                                      }else {
                                                        Navigator.of(context)
                                                            .pop();
                                                        final pickedFile = await picker
                                                            .pickImage(
                                                            source: ImageSource
                                                                .gallery);

                                                        if (pickedFile != null) {
                                                          setState(() {
                                                            oneCheck = 2;
                                                            _userImage2 = File(
                                                                pickedFile.path);
                                                            printImageMemorySize(
                                                                _userImage2!);
                                                            print(_userImage2);
                                                            compressImage(
                                                                _userImage2!);
                                                          });
                                                        }
                                                      }
                                                    },
                                                  ),

                                                  SizedBox(width: 38.w,),
                                                  GestureDetector(
                                                    child: Column(
                                                      children: [
                                                        Image.asset(
                                                          "lib/Images/Authentication/拍照icon.png",
                                                          width: 35.w,
                                                          height: 35.h,),
                                                        Text(messages["拍照"],
                                                          style: TextStyle(
                                                              color: Colors
                                                                  .black),),

                                                      ],

                                                    ),
                                                    onTap: () async {
                                                      var status = await Permission.camera.request();
                                                      if(status==PermissionStatus.denied){
                                                        showCameraFirstDialog(context);
                                                      }else if(status==PermissionStatus.permanentlyDenied){
                                                        showCameraDialog(context);
                                                      }else {
                                                        Navigator.of(context)
                                                            .pop();
                                                        final pickedFile = await picker
                                                            .pickImage(
                                                            source: ImageSource
                                                                .camera);

                                                        if (pickedFile != null) {
                                                          setState(() {
                                                            oneCheck = 2;
                                                            _userImage2 = File(
                                                                pickedFile.path);
                                                            printImageMemorySize(
                                                                _userImage2!);
                                                            print(_userImage2);
                                                            compressImage(
                                                                _userImage2!);
                                                          });
                                                        }
                                                      }
                                                    },
                                                  ),

                                                ],
                                              ),
                                              SizedBox(height: 30.h,),
                                            ],

                                          ),

                                        ],

                                      ),
                                    );
                                  });
                            }
                          },
                        ),


                      ],
                    ),




                  ],
                ) ,
              ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                height: 340.h,
                child:  ListView.separated(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount:7,
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(  // 这里使用 Divider 作为分隔符
                        color: Color.fromRGBO(248, 248, 248, 1),
                        height: 8.h,  // 分隔符的高度
                      );
                    },
                    itemBuilder:(context, index) {
                      return Padding(padding:

                      EdgeInsets.only(left: 8.w,right: 8.w),
                        child: GestureDetector(
                            child: Container(height: 40.h,
                          decoration: BoxDecoration(
                              border: Border.all(
                                color:isShowError==true&&dataList[index]==''? Colors.red:Colors.white, // 边框颜色
                                width: 0.5, // 边框宽度
                              ),
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  SizedBox(width: 8.h,),
                                  Text(titleList[index],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                ],
                              ),
                                Row(
                                    children: [
                                      if(index==5)
                                        Container(
                                          width: screenSize.width-180.w,
                                          child: Text(dataList[index],textAlign: TextAlign.right,style: TextStyle(color:Colors.black,overflow:TextOverflow.ellipsis,fontSize:14.sp ),),
                                        ),
                                      if(index!=5)
                                        Container(
                                          width: screenSize.width-180.w,
                                          child: Text(dataList[index],textAlign: TextAlign.right,style: TextStyle(color:Colors.black,overflow:TextOverflow.ellipsis,fontSize:14.sp ),),
                                        ),
                                      isEdit?
                                      Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 14,):SizedBox(width: 10.w,),
                                    ],
                                  ),



                            ],
                          ),
                          ),
                            onTap: () async {
                              if (isEdit) {
                                if (index == 3) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[3] = Time;
                                      cardModel.StartTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.StartTime;
                                    });
                                  }
                                } else if (index == 4) {
                                  final result = await showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return dataTimeSheet(
                                      );
                                    },
                                  );

                                  if (result != null) {
                                    String mounth = "";
                                    String day = "";

                                    setState(() {
                                      if (result[1]
                                          .toString()
                                          .length == 1) {
                                        mounth = result[1].toString().padLeft(
                                            2, '0');
                                      } else {
                                        mounth = result[1].toStringAsFixed(0);
                                      }
                                      if (result[2]
                                          .toString()
                                          .length == 1) {
                                        day = result[2].toString().padLeft(
                                            2, '0');
                                      } else {
                                        day = result[2].toStringAsFixed(0);
                                      }

                                      String Time = result[0].toString() + "-" +
                                          mounth + "-" + day;
                                      dataList[4] = Time;
                                      cardModel.EndTime = Time;
                                      _nametextEditingController.text =
                                          cardModel.EndTime;
                                    });
                                  }
                                } else {
                                  _nametextEditingController.text =
                                  dataList[index];
                                  showModalBottomSheet(
                                      isDismissible: false,
                                      context: context,

                                      builder: (BuildContext context) {
                                        return Container(

                                          decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(10))),
                                          child: Column(

                                            children: [

                                              SizedBox(height: 8.h,),
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment
                                                    .spaceBetween,
                                                children: [
                                                  TextButton(onPressed: () {
                                                    Navigator.of(context)
                                                        .pop();
                                                    setState(() {
                                                      if (index == 0) {
                                                        cardModel.name =
                                                        dataList[index];
                                                      } else if (index == 1) {
                                                        cardModel
                                                            .DriverNum =
                                                        dataList[index];
                                                      } else if (index == 2) {
                                                        cardModel.CarStyle =
                                                        dataList[index];
                                                      } else
                                                        // if (index == 3) {
                                                        //   cardModel
                                                        //       .StartTime =
                                                        //   dataList[index];
                                                        // } else
                                                        // if (index == 4) {
                                                        //   cardModel.EndTime =
                                                        //   dataList[index];
                                                        // } else
                                                      if (index == 5) {
                                                        cardModel
                                                            .CardOfficeName =
                                                        dataList[index];
                                                      } else if (index == 6) {
                                                        cardModel.FileNum =
                                                        dataList[index];
                                                      }
                                                      _nametextEditingController
                                                          .text =
                                                      dataList[index];
                                                    });
                                                  },
                                                      child: Text(
                                                        messages["取消"],
                                                        style: TextStyle(
                                                            color: Colors
                                                                .black,
                                                            fontSize: 14.sp),)),
                                                  Text(titleList[index] +
                                                      "输入",
                                                    style: TextStyle(
                                                        color: Colors.black,
                                                        fontSize: 16.sp,
                                                        fontWeight: FontWeight
                                                            .w600),),
                                                  TextButton(onPressed: () {
                                                    Navigator.of(context)
                                                        .pop();

                                                    setState(() {
                                                      if (index == 0) {
                                                        dataList[index] =
                                                            cardModel.name;
                                                      } else if (index == 1) {
                                                        dataList[index] =
                                                            cardModel
                                                                .DriverNum;
                                                      } else if (index == 2) {
                                                        dataList[index] =
                                                            cardModel
                                                                .CarStyle;
                                                      } else if (index == 3) {
                                                        dataList[index] =
                                                            cardModel
                                                                .StartTime;
                                                      } else if (index == 4) {
                                                        dataList[index] =
                                                            cardModel
                                                                .EndTime;
                                                      } else if (index == 5) {
                                                        dataList[index] =
                                                            cardModel
                                                                .CardOfficeName;
                                                      } else if (index == 6) {
                                                        dataList[index] =
                                                            cardModel
                                                                .FileNum;
                                                      }
                                                      _nametextEditingController
                                                          .text =
                                                      dataList[index];
                                                    });
                                                  },
                                                    child: Text(
                                                      messages["确定"],
                                                      style: TextStyle(
                                                          color: Color
                                                              .fromRGBO(
                                                              231, 112, 27,
                                                              0.85),
                                                          fontSize: 14.sp),),),
                                                ],
                                              ),
                                              SizedBox(height: 8.h,),
                                              Container(

                                                margin: EdgeInsets.only(
                                                    left: 18.w,
                                                    right: 18.w),
                                                decoration: BoxDecoration(
                                                  borderRadius: BorderRadius
                                                      .circular(30.0),

                                                ),
                                                child: TextField(
                                                  // keyboardType: TextInputType.number,
                                                    controller: _nametextEditingController,
                                                    keyboardType: index==6?TextInputType.number: TextInputType.text,
                                                    style: TextStyle(
                                                      color: Colors.black,
                                                    ),
                                                    decoration: InputDecoration(
                                                      filled: true,
                                                      fillColor: Color
                                                          .fromRGBO(
                                                          249, 249, 249, 1),
                                                      border: InputBorder
                                                          .none,


                                                    ),
                                                    onChanged: (text) {
                                                      setState(() {
                                                        if (index == 0) {
                                                          cardModel.name =
                                                              text;
                                                          print(cardModel
                                                              .name);
                                                        } else if (index == 1) {
                                                          cardModel
                                                              .DriverNum =
                                                              text;
                                                        } else if (index == 2) {
                                                          cardModel
                                                              .CarStyle =
                                                              text;
                                                        } else if (index == 3) {
                                                          cardModel
                                                              .StartTime =
                                                              text;
                                                        } else if (index == 4) {
                                                          cardModel
                                                              .EndTime =
                                                              text;
                                                        } else if (index == 5) {
                                                          cardModel
                                                              .CardOfficeName =
                                                              text;
                                                        } else if (index == 6) {
                                                          cardModel
                                                              .FileNum =
                                                              text;
                                                        }
                                                      });
                                                    }
                                                ),
                                              ),

                                            ],
                                          ),
                                        );
                                      });
                                }
                              }
                            }
                        ),
                      );
                    }
                ),
              ),
            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color:MyColors.themeColor,
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text(isEdit? "提交审核":"编辑",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: () async {
                        if(isEdit==false){
                          setState(() {
                            isEdit=true;
                          });
                        }else {
                          setState(() {
                            isShowError=true;
                          });
                          if (dataList[0] == "") {
                            BrnToast.show(
                              "请输入姓名", context, duration: BrnDuration
                                .short,);
                          }
                          else if (dataList[1] == "") {
                            BrnToast.show(
                              "请输入驾驶证号", context, duration: BrnDuration
                                .short,);
                          }
                          else if (dataList[2] == "") {
                            BrnToast.show("请输入准驾车型", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[3] == "") {
                            BrnToast.show("请选择有效起始日期", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[4] == "") {
                            BrnToast.show("请选择有效截止日期", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[5] == "") {
                            BrnToast.show("请输入发证机关", context,
                              duration: BrnDuration.short,);
                          }
                          else if (dataList[6] == "") {
                            BrnToast.show("请输入档案编号", context,
                              duration: BrnDuration.short,);
                          }
                          else if (getbackPath == "" || getfrontPath == "") {
                            BrnToast.show("请添加驾驶证图片", context,
                              duration: BrnDuration.short,);
                          }

                          else {
                            String? drvId = await UserIdManager.getUserID();
                            ApiManager.postData(
                              context,
                              'api/auth/driver/user/editDriverLicenseInfo',
                              {
                                "realName": dataList[0],
                                "fileNum": dataList[6],
                                "licenseNum": dataList[1],
                                "vehicleClass": dataList[2],
                                "validPeriodFrom": dataList[3],
                                "validPeriodTo": dataList[4],
                                "issuingOrganizations": dataList[5],
                                // "frontPath": "sph56/driver/1781255212293775361/avatar/1781255212293775361_avatar.png",
                                // "backPath": "sph56/driver/1781255212293775361/avatar/1781255212293775361_avatar.png",
                                "frontPath": getfrontPath,
                                "backPath": getbackPath
                              },
                                  (responseData) async {
                                BrnToast.show("提交成功", context,);
                                Navigator.pop(context, "success");
                              },
                            );
                          }
                        }
                      },
                    )
                ),
              ],
            ),
          ),



          // }),
        ],
      ),

    );
  }
}
class dataTimeSheet extends StatefulWidget {
  const dataTimeSheet({super.key, });

  @override
  State<dataTimeSheet> createState() => _dataTimeSheetState();
}

class _dataTimeSheetState extends State<dataTimeSheet> {
  DateTime selectedDate = DateTime.now();
  int selectedYear = DateTime.now().year;
  int selectedMonth = DateTime.now().month;
  int selectedDay = DateTime.now().day;
  int selectedHour = DateTime.now().hour;
  late List<int> years;
  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController dayController;
  late FixedExtentScrollController hourController;
  @override
  void initState() {
    super.initState();

    DateTime selectedDate = DateTime.now();
    int selectedYear = DateTime.now().year;
    int selectedMonth = DateTime.now().month;
    int selectedDay = DateTime.now().day;
    int selectedHour = DateTime.now().hour;
    int currentYear = DateTime.now().year;
    years = List.generate(6, (index) => currentYear + index);
    // 设置初始滚动位置
    yearController = FixedExtentScrollController(initialItem: years.indexOf(selectedYear));
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
    hourController = FixedExtentScrollController(initialItem: selectedHour);
  }
  @override
  int getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }

  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.w,bottom: 40.h),
        height: 350.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Colors.white,
        ),
        child:Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(onPressed: (){
                  Navigator.pop(context);
                }, child: Text("取消",style: TextStyle(color: Colors.black),)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.access_time,color: MyColors.textColor,),
                    Text("选择日期",style:TextStyle(color: Colors.black,fontSize: 16.sp),),
                  ],
                ),
                TextButton(onPressed: (){

                  print([selectedYear,selectedMonth,selectedDay,selectedHour]);
                  Navigator.pop(context,[selectedYear,selectedMonth,selectedDay,selectedHour]);
                }, child: Text("确定",style: TextStyle(color: MyColors.themeColor,))),
              ],
            ),

            Divider(height: 16.h,color: MyColors.backgreyColor,),
            Text("时间格式:年-月-日",style: TextStyle(color: Colors.black),),
            SizedBox(height: 4.h,),
            Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: Color.fromRGBO(224, 227, 234, 1),
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(5.0), // 可选，添加圆角
              ),
              child:  Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildPicker(
                    items: generateYearList(),
                    controller: yearController,
                    onChanged: (value) {
                      setState(() {
                        selectedYear = value;
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(12, (index) => index + 1),
                    controller: monthController,
                    onChanged: (value) {
                      setState(() {
                        selectedMonth = value;
                      });
                    },
                  ),
                  _buildPicker(
                    items: List.generate(getDaysInMonth(selectedYear, selectedMonth), (index) => index + 1),
                    controller: dayController,
                    onChanged: (value) {
                      setState(() {
                        selectedDay = value;
                      });
                    },
                  ),
                  // _buildPicker(
                  //   items: List.generate(24, (index) => index),
                  //   controller: hourController,
                  //   onChanged: (value) {
                  //     setState(() {
                  //       selectedHour = value;
                  //     });
                  //   },
                  // ),
                ],
              ),
            ),
            SizedBox(height: 9.h,),

          ],
        )



    );
  }
  Widget _buildPicker({
    required List<int> items,
    required FixedExtentScrollController controller,
    required ValueChanged<int> onChanged,
  }) {
    return Container(
      height: 150.0,
      width: 100.0,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (index) {
          onChanged(items[index]);
        },
        selectionOverlay: _buildSelectionOverlay(),
        children: items.map((item) => _buildPickerItem(item)).toList(),
        // 使用初始化的控制器
        scrollController: controller,
      ),
    );
  }

  Widget _buildPickerItem(int item) {
    // 将月份和日期格式化为两位数
    String formattedItem = item.toString().padLeft(2, '0');

    return Container(
      alignment: Alignment.center,
      child: Text(formattedItem),
    );
  }

  Widget _buildSelectionOverlay() {
    return Container(
      height: 40.0,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
          bottom: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
        ),
      ),
    );
  }

  // 生成年份列表，包括当前年份和之后的5年
  List<int> generateYearList() {
    int currentYear = DateTime.now().year;
    List<int> years = List.generate(6, (index) => currentYear + index);
    return years;
  }
}